package com.example.backspring.config;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtil {
    private static final String KEY = "a14124faf8bc40ae"; // 16 字节密钥

    public static String encrypt(String data) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String encrypted) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted));
            return new String(original);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String original = "66292e16-6591-4879-8423-e0d52d8619e5";
        String encrypted ="EjjU4lulHETmDMC13C5GaBsebNEPD7mY7YtN13lBlhE%3D";
        System.out.println("加密后的文本: " + encrypted);
        // 传输加密后的文本 6CQTIgQYGsQvm7ZoMhd9G4MNAxGl6eVTLx15AraYmHEgZWlc8mNtIBo7DcxWNuzd
        String decrypted = decrypt(encrypted);
        System.out.println("解密后的文本: " + decrypted);

        // 进行 token 验证或其他逻辑
        if (original.equals(decrypted)) {
            System.out.println("Token 验证成功");
        } else {
            System.out.println("Token 验证失败");
        }
    }
}
